//
//  ComposeViewController.swift
//  WeiBlog
//
//  Created by apple on 15/10/24.
//  Copyright © 2015年 xiang. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {
    
    // MARK: ----视图周期相关
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // MARK: 添加键盘通知,监听键盘frame变化(注意通知名)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func loadView() {

        view = UIView()
        //print(view) //这时候view的frame是0
        //放在不同的地方会有不同程度的卡顿,在点击加好按钮时
        setUI()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        //当图片选择器不显示的时候,才显示键盘
        if pictureCollectionController.view.bounds.height == 0{
            
            textView.becomeFirstResponder()
        }
        
        
    }

    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK:----通知事件
    ///通知的监听方法(toolBar的动画)
    @objc private func keyboardChangeFrame(n:NSNotification){
//        print(n.userInfo)
//            [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 667}, {375, 258}},
//            UIKeyboardCenterEndUserInfoKey: NSPoint: {187.5, 538},
//            UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {375, 258}},
//            UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 409}, {375, 258}},
//            UIKeyboardAnimationDurationUserInfoKey: 0.25,
//            UIKeyboardCenterBeginUserInfoKey: NSPoint: {187.5, 796},
//            UIKeyboardAnimationCurveUserInfoKey: 7,
//            UIKeyboardIsLocalUserInfoKey: 1])
        let info = n.userInfo
        //取键盘结束时的frame
        let y = (info![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().origin.y
        let offset = -(UIScreen.mainScreen().bounds.height - y)
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        //取动画时间(这是为了让toolBar能和键盘的动画保持一直)
        let duration = (info![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //取curve值
        /**
        case EaseInOut // slow at beginning and end(先加再减)
        case EaseIn // slow at beginning(加速)
        case EaseOut // slow at end(减速)
        case Linear
            这个值,是来设置动画渐变效果的,一般值是0-3,当值是7
        的时候,在当前动画没完成的情况下,又执行了一个动画,那么就直接执行后面这个动画,
        - 这里切换键盘时,键盘下去是一个动画,再次叫出是另一个动画,这样的效果就是过度很平滑
        */
        let curve = (info![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue
        let aniCurve = UIViewAnimationCurve(rawValue: Int(curve))

        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(aniCurve!)//这个不设置就会发现每次切换键盘时,toolBar会抖动
            self.view.layoutIfNeeded()
            }
    }
    // MARK:-------监听事件
    ///  关闭barbuttonitem的点击
    @objc private func close(){
        
        //先释放键盘
        textView.resignFirstResponder()
        
       dismissViewControllerAnimated(true, completion: nil)
    }
    
    ///  发送barbuttonitem的点击
    @objc private func compose(){
        //这里是要调用网络接口的
        NetworkManager.sharedManager.composeStatus(textView.text) { (resultData, error) -> () in
            //返回的数据是一条微博数据
            print(resultData)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.close()
        }
    }
    
    /// 表情按钮的点击
    @objc private func emoticonButtonClick(){
        
        //要想切换键盘,在键盘弹出后,是不能修改的(强引用),想要修改,必须先释放键盘,也就是该键盘,必须在键盘出来前改
        textView.resignFirstResponder()
        //接着切换键盘(注意一个点:当是原生键盘,inputView == nil)
        //三目运算保证键盘可以互相切换
        textView.inputView = textView.inputView != nil ? nil:UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 216))
        //最后调出键盘
        textView.becomeFirstResponder()
    }
    
    ///图片选择按钮的点击
    @objc private func pictureButtonClick(){
        
        
        textView.resignFirstResponder()
        
        let height = pictureCollectionController.view.bounds.height == 0 ? (view.bounds.height * 0.6) : 0
        
        pictureCollectionController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(height)
        }
        
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.width.equalTo(ScreenWidth)
            make.bottom.equalTo(pictureCollectionController.view.snp_top)
        }
        
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK:-------懒加载
    
    /// 输入文本框
    private lazy var textView:UITextView = {
        let textV = UITextView()
        textV.textColor = UIColor.lightGrayColor()
        textV.font = UIFont.systemFontOfSize(17)
        //这是设置textView能一直允许垂直拖拽
        textV.alwaysBounceVertical = true
        //拖拽时,隐藏键盘
        textV.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        textV.delegate = self
        return textV
        }()
    ///tooBar
    private lazy var toolBar:UIToolbar = UIToolbar()
    ///文本框里的展位label
    private lazy var placeHolderLabel:UILabel = UILabel(text: "分享新鲜事...", fontSize: 17, color: UIColor.lightGrayColor(), screenSet: 0)
    /// 图片选择控制器
    private lazy var pictureCollectionController:PictureCollectionController = PictureCollectionController()
    
}
// MARK: ---- 输入监听
extension ComposeViewController:UITextViewDelegate
{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}
// MARK:-------设置整体界面
extension ComposeViewController
{
    private func setUI(){
        view.addSubview(textView)
        view.addSubview(toolBar)
        //顶部bar
        setTopBar()
        //textView
        setTextView()
        //设置图片选择器
        setPictureCollectionController()
        //底部toolBar
        setToolBar()
    }
    
    ///  顶部bar
    private func setTopBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "compose")
        //没输入时
        navigationItem.rightBarButtonItem?.enabled = false
        
        let vw = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 32))
        let label1 = UILabel(text: "发布微博", fontSize: 13)
        let label2 = UILabel(text: (UserAccountViewModel.sharedUserAccountViewModel.userAccountInfo?.screen_name)!, fontSize: 12, color: UIColor.lightGrayColor())
        vw.addSubview(label1)
        vw.addSubview(label2)
        label1.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(vw.snp_top)
            make.centerX.equalTo(vw)
        }
        label2.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(label1.snp_bottom)
            make.centerX.equalTo(vw)
        }
        navigationItem.titleView = vw
    }
    
    ///  textView
    private func setTextView(){
        
        //注意:
        /**
            在ios7 之后,如果有'滚动视图'和 navigationBar 的组合时,那么系统会"自动"将'滚动视图'的contentSize压缩一个Bar的距离
        现在不需要这个属性,设为false就行了
        */
        automaticallyAdjustsScrollViewInsets = false
        
        //自动布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            //            make.top.equalTo(view.snp_top)
            make.width.equalTo(ScreenWidth)
            make.bottom.equalTo(toolBar.snp_top)
        }
        //添加占位lable
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    ///  底部toolbar
    private func setToolBar(){
        //自动布局
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.width.equalTo(ScreenWidth)
        }
        //添加items
        addItems()
    }
    
    /// 添加item到toolBar上
    private func addItems(){
        //注意这样定义的好处
        let dictArr = [["imageName":"compose_emoticonbutton_background","actionName":"emoticonButtonClick"],
            ["imageName":"compose_mentionbutton_background"],
            ["imageName":"compose_toolbar_picture","actionName":"pictureButtonClick"],
            ["imageName":"compose_camerabutton_background"],
            ["imageName":"compose_photo_video"]]
        var items = [UIBarButtonItem]()
        // 遍历字典,给toolBar添加item
        for d in dictArr{
            
            let btn = UIButton(title: nil, fontSize: nil, color: nil, bgImageName: nil, imageName: d["imageName"], actionName: d["actionName"], target: self)
            
            let barItem  = UIBarButtonItem(customView: btn)
            
            items.append(barItem)
            
            let flexibleItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            items.append(flexibleItem)
        }
        
        //移除最后一个弹簧
        items.removeLast()
        //添加到toolbars上面
        toolBar.items = items
    }
    
    /// 设置图片选择控制器
    private func setPictureCollectionController(){
        
        addChildViewController(pictureCollectionController)
        
        view.insertSubview(pictureCollectionController.view, belowSubview: toolBar)
        
        pictureCollectionController.view.snp_makeConstraints { (make) -> Void in
            make.height.equalTo(view.frame.height * 0.6)//此时布局view的frame是0
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
        }
    }
}

